package service

import (
	"errors"
	"wms/internal/model"
	"wms/internal/model/request"
	"wms/pkg/database"
	"wms/pkg/logger"

	"gorm.io/gorm"
)

// SupplierService 供应商服务
type SupplierService struct {
	db *gorm.DB
}

// NewSupplierService 创建供应商服务
func NewSupplierService() *SupplierService {
	return &SupplierService{
		db: database.GetDB(),
	}
}

// CreateSupplier 创建供应商
func (s *SupplierService) CreateSupplier(req *request.SupplierCreateRequest, userID uint) error {
	var existingSupplier model.Supplier
	err := s.db.Where("name = ?", req.Name).First(&existingSupplier).Error
	if err == nil {
		return errors.New("供应商名称已存在")
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}

	// 检查联系电话是否存在
	if req.Phone != "" {
		err = s.db.Where("phone = ?", req.Phone).First(&existingSupplier).Error
		if err == nil {
			return errors.New("联系电话已存在")
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
	}

	supplier := model.Supplier{
		Name:    req.Name,
		Contact: req.Contact,
		Phone:   req.Phone,
		Email:   req.Email,
		Address: req.Address,
		// Remark:  req.Remark, // Removed reference to non-existent field
	}

	err = s.db.Create(&supplier).Error
	if err == nil {
		// 记录数据操作日志
		logger.LogDataOperation("创建供应商", userID, "供应商", supplier.ID, supplier.Name, "创建")
	}
	return err
}

// UpdateSupplier 更新供应商
func (s *SupplierService) UpdateSupplier(req *request.SupplierUpdateRequest, userID uint) error {
	var supplier model.Supplier
	err := s.db.First(&supplier, req.ID).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("供应商不存在")
		}
		return err
	}

	// 检查名称是否存在
	if req.Name != supplier.Name {
		var existingSupplier model.Supplier
		err := s.db.Where("name = ? AND id != ?", req.Name, req.ID).First(&existingSupplier).Error
		if err == nil {
			return errors.New("供应商名称已存在")
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
	}

	// 检查联系电话是否存在
	if req.Phone != "" && req.Phone != supplier.Phone {
		var existingSupplier model.Supplier
		err := s.db.Where("phone = ? AND id != ?", req.Phone, req.ID).First(&existingSupplier).Error
		if err == nil {
			return errors.New("联系电话已存在")
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
	}

	// 更新供应商信息
	updates := map[string]interface{}{
		"name":    req.Name,
		"contact": req.Contact,
		"phone":   req.Phone,
		"email":   req.Email,
		"address": req.Address,
		// "remark":  req.Remark, // Removed reference to non-existent field
	}

	err = s.db.Model(&supplier).Updates(updates).Error
	if err == nil {
		// 记录数据操作日志
		logger.LogDataOperation("更新供应商", userID, "供应商", req.ID, req.Name, "更新")
	}
	return err
}

// DeleteSupplier 删除供应商
func (s *SupplierService) DeleteSupplier(id uint, userID uint) error {
	// 检查供应商是否存在
	var supplier model.Supplier
	err := s.db.First(&supplier, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("供应商不存在")
		}
		return err
	}

	// TODO: 检查供应商是否有关联的订单，如果有则不允许删除

	err = s.db.Delete(&supplier).Error
	if err == nil {
		// 记录数据操作日志
		logger.LogDataOperation("删除供应商", userID, "供应商", id, supplier.Name, "删除")
	}
	return err
}

// GetSupplierByID 根据ID获取供应商
func (s *SupplierService) GetSupplierByID(id uint) (*model.Supplier, error) {
	var supplier model.Supplier
	err := s.db.First(&supplier, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("供应商不存在")
		}
		return nil, err
	}
	return &supplier, nil
}

// ListSuppliers 获取供应商列表
func (s *SupplierService) ListSuppliers(req *request.SupplierListRequest) ([]model.Supplier, int64, error) {
	var suppliers []model.Supplier
	var total int64

	query := s.db.Model(&model.Supplier{})

	// 根据条件筛选
	if req.Keyword != "" {
		query = query.Where("name LIKE ? OR contact LIKE ? OR phone LIKE ?",
			"%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}

	// 统计总数
	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	err = query.Offset(offset).Limit(req.PageSize).Find(&suppliers).Error
	if err != nil {
		return nil, 0, err
	}

	return suppliers, total, nil
}
